package com.fary.utils;

import cn.hutool.extra.spring.SpringUtil;
import com.fary.config.JacksonConfig.CustomizeBeanSerializerModifier;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.SerializerFactory;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

public class XmlMapperUtil {

    private static volatile XmlMapper xmlMapper;

    private static XmlMapper getXmlMapper() {
        if (xmlMapper == null) {
            synchronized (XmlMapperUtil.class) {
                if (xmlMapper == null) {
//                    xmlMapper = new XmlMapper();
                    Jackson2ObjectMapperBuilder builder = SpringUtil.getBean(Jackson2ObjectMapperBuilder.class);
                    ObjectMapper objectMapper = builder.createXmlMapper(true).build();
                    SerializerFactory serializerFactory = objectMapper.getSerializerFactory().withSerializerModifier(new CustomizeBeanSerializerModifier());
                    objectMapper.setSerializerFactory(serializerFactory);
                    xmlMapper = (XmlMapper) objectMapper;
                    xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
                }
            }
        }
        return xmlMapper;
    }

    public static String writeToXml(Object value) {
        try {
            return getXmlMapper().writeValueAsString(value);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static <T> T readToObject(String xml, Class<T> type) {
        try {
            return getXmlMapper().readValue(xml, type);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 }
